import React, { useEffect, useState } from "react";
import { Input, Tree, TreeProps } from "antd";

import ProBox from "vendor/components/pro-box";
import ProAutoScrollbars from "vendor/components/pro-autoScrollbars";

import { useTreeData } from "./useTreeData";

interface DeptTreeProps extends TreeProps {
  onOrgChange?: (deptId: number) => void;
  isAllowCancelSelected?: boolean;    // 是否允许取消选中
}

const DeptTree: React.FC<DeptTreeProps> = ({ onOrgChange, isAllowCancelSelected = true, ...restProps }) => {
  const headerHeight = 32;
  const { loading, treeData, expandedKeys, autoExpandParent,onExpand, onSearch } = useTreeData();
  const [selectedDeptId, setSelectedDeptId] = useState<number>();

  useEffect(() => {
    if (treeData.length > 0) {
      const deptId = treeData[0].key;
      setSelectedDeptId(deptId as number);
      onOrgChange && onOrgChange(deptId as number);
    }
  }, [treeData])

  return (
    <div style={{ height: "100%", padding: 5 }}>
      <Input.Search
        style={{ height: headerHeight }}
        placeholder="请输入组织名称"
        // onSearch={(value) => fetchDeptTreeData({ deptName: value })}
        onSearch={(value) => onSearch(value)}
        enterButton
        allowClear
      />

      <div style={{ paddingTop: 8, height: `calc(100% - ${headerHeight}px)` }}>
        <ProBox loading={loading}>
          <ProAutoScrollbars>
            <Tree
              treeData={treeData}
              // defaultExpandedKeys={(treeData && treeData.length > 0) ? [treeData[0].key] : []}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
              selectedKeys={[selectedDeptId]}
              selectable={true}
              blockNode={true}
              onExpand={onExpand}
              onSelect={(selectedKeys) => {
                if (!isAllowCancelSelected && selectedKeys.length == 0) return;
                const deptId = selectedKeys[0] as number;
                setSelectedDeptId(deptId);
                onOrgChange && onOrgChange(deptId);
              }}
              {...restProps}
            />
          </ProAutoScrollbars>
        </ProBox>
      </div>
    </div>
  )
}


export default DeptTree;
